import { showToast } from 'vant';
import api from '../api';
import store from './store';
interface PayConfig<T = any> {
    appId: string;
    timeStamp: number;
    nonceStr: string;
    packageStr?: string;
    signType?: string;
    paySign?: string;
}

// 判断是否为微信浏览器
export const isIOS = () => {
    const userAgent = navigator.userAgent.toLowerCase();
    return /iphone|ipad|ipod/.test(userAgent);
};

// 判断是否为Android设备
export const isAndroid = () => {
    const userAgent = navigator.userAgent.toLowerCase();
    return /android/.test(userAgent);
};

/**
 *  随机数
 */
export const uuid = (len, radix) => {
    const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    const uuid = [];
    let i;
    radix = radix || chars.length;
    if (len) {
        // Compact form
        for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)];
    } else {
        // rfc4122, version 4 form
        let r;
        // rfc4122 requires these characters
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
        uuid[14] = '4';
        // Fill in random data.  At i==19 set the high bits of clock sequence as
        // per rfc4122, sec. 4.1.5
        for (i = 0; i < 36; i++) {
            if (!uuid[i]) {
                r = 0 | (Math.random() * 16);
                uuid[i] = chars[i === 19 ? (r & 0x3) | 0x8 : r];
            }
        }
    }

    return uuid.join('');
};

/**
 *  方法名：
 *    isNull 判断是否为undefined、""、null、{}、[]
 *  参数：
 *    value
 *  返回
 *    true false
 */
const isNull = (value) => {
    let flag = false;
    const getType = Object.prototype.toString;
    const vtype = getType.call(value);
    if (vtype === '[object String]') {
        flag =
            value.toString().trim() === '' ||
            value.toString().trim() === 'undefined' ||
            value.toString().trim() === '{}';
    } else if (vtype === '[object Undefined]') {
        flag = value === undefined ? true : false;
    } else if (vtype === '[object Null]') {
        flag = value === null ? true : false;
    } else if (vtype === '[object Object]') {
        flag = JSON.stringify(value) === '{}' ? true : false;
    } else if (vtype === '[object Array]') {
        flag = value.length === 0 ? true : false;
    }
    return flag;
};

/**
 * 格式化时间
 * @param {*} time
 * @param {*} cFormat
 */
export const formatDate = (time, cFormat) => {
    if (!time && !cFormat) {
        return null;
    }
    if (isNull(time)) {
        return '';
    }
    const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}';
    let date;
    if (typeof time === 'object') {
        date = time;
    } else {
        if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
            if (time.toString().length > 8) {
                time = parseInt(time);
            } else {
                time =
                    time.substring(0, 4) + '/' + time.substring(4, 6) + '/' + time.substring(6, 8);
            }
        } else if (typeof time === 'number') {
            if (time.toString().length === 10) {
                time = time * 1000;
            }
        } else {
            time = time.replace(/-/g, '/').replace(/T/g, ' ').split('.')[0];
        }
        // console.log(time, 'time15')
        date = new Date(time);
    }

    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    };
    const timeStr = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key];
        if (key === 'a') {
            return ['日', '一', '二', '三', '四', '五', '六'][value];
        }
        if (result.length > 0 && value < 10) {
            value = '0' + value;
        }
        return value || 0;
    });

    return timeStr;
};

/**
 * 页面跳转
 * @param router
 * @param params
 *  routerType 跳转类型  replace 替换，href跳转，默认跳转
 *  isBlank 是否新开页面，router 为带http完整地址
 *  cacheKey 需要缓存的key，有key时就缓存
 *  cacheValue 需要缓存的值，默认缓存传入的params
 */
export const navigateTo = (router: string, params: any = {}) => {
    const { routerType = 'href', isBlank = false, cacheKey = '', cacheValue } = params || {};
    cacheKey && store.set(cacheKey, cacheValue || params);
    let context = '';
    //  isBlank 新开页面时，context为空
    if (!isBlank) {
        context = getContextPath();
    }
    if (routerType === 'replace') {
        location.replace(`${context}${router}`);
    } else {
        location.href = `${context}${router}`;
    }
};

/**
 * 检查是否运行在微信环境
 * @returns
 */
export const checkEnvConfig = () => {
    let curEnv = '';
    const ua = window.navigator.userAgent;
    //判断是不是微信
    if (ua.indexOf('MicroMessenger') >= 0) {
        curEnv = 'WeiXIN';
        // 微信pc浏览器
        if (ua.indexOf('WindowsWechat') >= 0) {
            console.log('WindowsWechat');
            return false;
        }
    }
    console.log('userAgent==', ua);
    if (curEnv === 'WeiXIN') {
        return true;
    }
    return false;
};

/**
 * 静默登录
 * @param code
 * @returns
 */
export const silentLogin = async (jsCode: string) => {
    try {
        const { code, message, data } = await api.fetchPost(
            'silentLogin',
            { code: jsCode },
            { hasErr: true }
        );
        if (code === 0) {
            store.set('USERINFO', data);
            console.log('userInfo==', data);
            return data;
        } else {
            showToast(message || '登录失败，请刷新页面');
        }
    } catch (err) {
        showToast('授权失败, 请重新扫码');
        console.log(err);
    }
};

/**
 * 获取二维码映射参数
 *
 * @param {*} idValue 映射id
 *
 */
export const getMapping = (idValue) => {
    return new Promise((resolve, reject) => {
        api.fetchGet('getMappingById', { idValue }, { hasErr: true, isLoading: false }).then(
            (res) => {
                const { data, code, message } = res;
                if (code === 0) {
                    resolve(data);
                } else {
                    showToast(message);
                    reject('');
                }
            }
        );
    });
};

/**
 * 获取url上面参数
 * @param name
 * @param url
 * @returns
 */
export const getUrlParam = (name: string, url?: string | undefined) => {
    const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`);
    const curStr = url ? url.split('?') : window.location.href.split('?');
    let r: any = '';
    if (curStr[1]) {
        r = curStr[1].match(reg); // search,查询？后面的参数，并匹配正则
        if (r !== null) return unescape(r[2]);
    }
    return r || '';
};

export const getContextPath = () => {
    let context = import.meta.env.VITE_PUBLIC_PATH;
    if (context === '/') {
        context = '';
    }
    return context;
};

/**
 * 获取微信授权地址
 * @param url '/web'
 * @param scopeType snsapi_base 静默；snsapi_userinfo获取头像昵称
 * @returns
 */
export const getAuthUrl = (url: string, scopeType?: string) => {
    const origin = window.location.origin;
    const context = getContextPath();
    const redirectUri = encodeURIComponent(`${origin}${context}${url}`);

    let appid = store.get('APP_ID');
    if (!appid) {
        appid = 'wx09e4568bbc2d5abf'; // 取不到appid就读线上的
    }

    let scope = 'snsapi_base';
    if (scopeType === 'snsapi_userinfo') {
        scope = 'snsapi_userinfo';
    }

    return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirectUri}&response_type=code&scope=${scope}&state=${appid}#wechat_redirect`;
};

/**
 * 公众号初始授权
 * @param callback
 */
export const getWxConfig = async (callback: any) => {
    const origin = window.location.origin;
    const context = getContextPath();
    let url = `${origin}${context}`;
    const localOrigin = import.meta.env.VITE_BASE_ORIGIN;
    if (localOrigin && localOrigin.indexOf('www.redgang.cn') >= 0) {
        url = `${localOrigin}${context}`;
    }
    try {
        const res = await api.fetchPost('getConfig', { url }, { hasErr: true });
        const { code, data, message } = res;
        if (code === 0) {
            typeof callback === 'function' && callback(data);
        } else {
            showToast(message);
        }
    } catch (err) {
        console.log('公众号config授权失败==', err);
    }
};

/**
 * 初始化公众号授权，index.html需要引用 <!-- <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script> -->
 * @param data
 */
export const initWxConfig = (data: any, callback: Function): void => {
    wx.config({
        debug: true,
        appId: data.appId,
        timestamp: data.timestamp,
        nonceStr: data.nonceStr,
        signature: data.signature,
        jsApiList: ['checkJsApi', 'chooseWXPay']
    });
    wx.ready(function () {
        callback && callback();
    });
};
/**
 * jsapi 第三方调起微信支付
 * 支付成功后，不支持回到业务页面，微信能力收回，改用点击计划  https://pay.weixin.qq.com/index.php/public/cms/content_detail?platformType=1&lang=zh&id=121505
 * @param data
 */
export const webRequestPayment = (data: PayConfig) => {
    const appId = store.get('APP_ID');
    function onBridgeReady() {
        WeixinJSBridge.invoke(
            'getBrandWCPayRequest',
            {
                appId, // 公众号id，由商户传入
                timeStamp: data.timeStamp, // 时间戳，自1970年以来的秒数
                nonceStr: data.nonceStr, // 随机串
                package: data.packageStr, // 订单详情扩展字符串
                signType: data.signType, // 微信签名方式:
                paySign: data.paySign // 微信签名
            },
            (res: any) => {
                console.log('支付回调 res=====', res);
                if (res.err_msg === 'get_brand_wcpay_request:ok') {
                    console.log('支付成功');
                } else if (res.err_msg == 'get_brand_wcpay_request:cancel') {
                    // showToast('支付取消');
                } else {
                    showToast('支付失败');
                }
            }
        );
    }

    if (typeof WeixinJSBridge === 'undefined') {
        if (document.addEventListener) {
            document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
        } else if (document.attachEvent) {
            document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
            document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
        }
    } else {
        onBridgeReady();
    }
};

/**
 * 影响公众号分享
 */
export const wxHideOptionMenu = () => {
    function onBridgeReady() {
        WeixinJSBridge.call('hideOptionMenu');
    }

    if (typeof WeixinJSBridge === 'undefined') {
        if (document.addEventListener) {
            document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
        } else if (document.attachEvent) {
            document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
            document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
        }
    } else {
        onBridgeReady();
    }
};

/**
 * jssdk公众号支付的场景，index.html需要引用 <!-- <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script> -->
 * 支付成功后，不支持回到业务页面，微信能力收回，改用点击计划  https://pay.weixin.qq.com/index.php/public/cms/content_detail?platformType=1&lang=zh&id=121505
 * @param data
 * @param callback
 */
export const weChatPay = (data: any) => {
    wx.ready(function () {
        const { timeStamp, nonceStr, packageStr, signType, paySign } = data;

        wx.chooseWXPay({
            timestamp: timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
            nonceStr: nonceStr, // 支付签名随机串，不长于 32 位
            package: packageStr, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
            signType: signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
            paySign: paySign, // 支付签名
            success: (res: any) => {
                // 前端判断返回方式，微信团队郑重提示：不保证绝对可靠，切记！
                if (res.errMsg == 'chooseWXPay:ok') {
                    console.log('支付成功');
                }
            },
            complete: (res: any) => {
                // 接口调用完成时执行的回调函数，无论成功或失败都会执行
                if (res.errMsg == 'chooseWXPay:ok') {
                    // 【支付成功】：支付成功提示页面，点击完成按钮之后
                    console.log('支付成功');
                    wx.closeWindow(); /* 关闭微信窗口，调用时需要在config中进行校验 */
                } else if (res.errMsg == 'chooseWXPay:cancel') {
                    // 【支付取消】
                    // showToast('取消支付');
                } else {
                    showToast('支付失败');
                }
                /**
                 * iOS和Android支付成功点击“完成”后都会进入success和complete函数，都返回'chooseWXPay:ok'
                 * （也有人说Android支付成功不进入success函数，）
                 * 原因是【iOS和Android返回数据不同。支付成功后Android返回 {"errMsg":"getBrandWCPayRequest:ok"}，iOS返回{"err_Info":"success","errMsg":"chooseWXPay:ok"}，故Android找不到success方法，导致失败】
                 * */
            }
        });
    });

    // wx.error(function (res: any) {
    //     console.log(res)
    //     showToast('授权失败')
    // });
};
